<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\DisclosureType;
use App\Services\DisclosureService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DisclosureTypeController extends Controller
{
    protected $DisclosureService;
    public function __construct(DisclosureService $DisclosureService)
    {
        $this->DisclosureService = $DisclosureService;
    }

    public function index(Request $Request) {
        $search = $Request->search;
        $limit = $Request->limit ?: 10;
        $page = $Request->page ?: 1;
        $page = $page * $limit - $limit;
        
        $sql = $this->DisclosureService->getType($search);
        if(Auth::user()->company_id > 0){
            $sql->where('project_id',$Request->project_id);
        }
        $total = $sql->count();
        $data = $sql->skip($page)->take($limit)->orderBy('created_at','desc')->get();
        return response()->json(['code' => '200', 'msg' => '操作成功','total'=>$total,'data'=>$data]);
    }

    /**
     * 存储一个新类型。
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $Request)
    {
        $POSTONLY = DisclosureType::POSTONLY;
        $input = $Request->only($POSTONLY);
        $data = $this->DisclosureService->insertType($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }


    public function update(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }

        $POSTONLY = DisclosureType::POSTONLY;
        $input = $Request->only($POSTONLY);
        $input['id'] = $Request->id;
        $data = $this->DisclosureService->updateType($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function delete(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }
        $data = DisclosureType::find($Request->id);
        $data->delete();
        return response()->json(['code' => '200', 'msg' => '操作成功']);
    }
}
